// < !--页面路径：store / index.js-- >
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
    state: {
        // 购物车数组
        cartList: uni.getStorageSync("cartList") || [],
        token: ''
    },
    mutations: {
        setCartList(state, cartList) {
            state.cartList = cartList
            uni.setStorageSync("cartList", cartList);
            // console.log(state.cartList)
        },
        setToken(state, token) {
            state.token = token

        }
    },
    getters: {
        // 总价格
        totalPrice(state) {
            let sum = 0;
            state.cartList.forEach((item) => {
                if (item.checked) {
                    sum += item.nums * item.goods_price;
                }
            });
            return sum;
        },
        // 总数量
        totalNum(state) {
            let num = 0;
            state.cartList.forEach((item) => {
                if (item.checked) {
                    num += item.nums;
                }
            });
            return num;
        },
        // 用户勾选了的商品数组
        checkedCartList(state) {
            return state.cartList.filter(item => item.checked)
        }
    }
})
export default store